
public class ChooseImageActivity extends AppCompatActivity implements ImagePickerAdapter.OnChooseListener, ImageFoldersAdapter.OnImageFolderChangeListener {

	//大致流程就是首先开线程扫描到所有图片路径
	//然后再展示在activity中
	//对于上层activity，返回的是路径数组
    private String mTitle,mFilePath;
    private int maxChoose;
    private TextView mTvTitle,mTvCommit,mTvImageTime,mTvImageFolders;
    private RecyclerView mRecyclerView;
    private ImageFolderPopupWindow mImageFolderPopupWindow;
    private ProgressDialog mProgressDialog;
    private RelativeLayout mRlBottom;
    private GridLayoutManager mGridLayoutManager;
    private ImagePickerAdapter mImagePickerAdapter;
    //图片路径list
    private List<String> mImagePaths;
    //图片对象list
    private List<ImageObject> imageObjectList;
    //文件夹list 
    private List<ImageFolder> mImageFolderList;
   
	
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_imagepicker);
        StatusBarCompat.setStatusBarColor(this, 0xfff2f2f2);

        initConfig();
		findAllId();
		setAllClick();
		//为recyclerView设置manager和adapter
        mProgressDialog = ProgressDialog.show(this, null, "请稍后");
		imageObjectList = new ArrayList<>();
		mImageFolderList = new ArrayList<>();
		mGridLayoutManager = new GridLayoutManager(this, 4);
        mImagePickerAdapter = new ImagePickerAdapter(this,imageObjectList);
        mImagePickerAdapter.setOnChooseListener(this);
		mRecyclerView.setLayoutManager(mGridLayoutManager);
		mRecyclerView.setAdapter(mImagePickerAdapter);
        
        getData();
    }

    //载入配置
    private void initConfig() {
        mTitle = getIntent().getStringExtra(EXTRA_TITLE);
        maxChoose = getIntent().getIntExtra(EXTRA_MAX_COUNT, 9);
		//设置最大选择数目
        SelectionManager.getInstance().setMaxCount(maxChoose);
		//设置图片集合
        mImagePaths = getIntent().getStringArrayListExtra(EXTRA_IMAGE_PATHS);
        if (mImagePaths == null) {
            SelectionManager.getInstance().removeAll();
        } else {
            SelectionManager.getInstance().addImagePathsToSelectList(mImagePaths);
        }
    }

    //载入数据
    private void getData() {
		//新建媒体扫描对象，并重写其callBack接口
		//注意接口要实现主线程中的方法
		//这里直接用runonuithread
		SerchPhoneImg serchPhoneImg = new SerchPhoneImg(context, mew SerchFinishCallBack(){
	      @Override
	      public void serchSuccess(final List<ImageFolder> imageFolderList) {
		    runOnUiThread(new Runnable() {
				@Override
				public void run() {
					//默认加载全部照片
					imageObjectList.addAll(imageFolderList.get(0).getImageObjectList());
					mImagePickerAdapter.notifyDataSetChanged();
					//图片文件夹数据
					mImageFolderList.addAll(imageFolderList);
					mImageFolderPopupWindow = new ImageFolderPopupWindow(ImagePickerActivity.this, mImageFolderList);
					mImageFolderPopupWindow.setAnimationStyle(R.style.imageFolderAnimator);
					mImageFolderPopupWindow.getAdapter().setOnImageFolderChangeListener(ImagePickerActivity.this);
					updateCommitButton();
					mProgressDialog.cancel();
				}
			});
	       }
	       @Override
	       public void serchFail() {
		      runOnUiThread(new Runnable() {
				@Override
				public void run() {
					Toast.makeText(ImagePickerActivity.this, "异常", Toast.LENGTH_SHORT).show();
					finish();
				}
			});
	       }
		});
		//开启线程去执行
	    new Thread() {
			public void run() {
		       serchPhoneImg.startSerch();
			}
		}.start;
    }

    //adapter中选择回调函数
    @Override
    public void onImageChoose(View view, int position) {
        //执行选中/取消操作
        //在同步数据的同时，同步UI
        ImageObject imageObject = mImagePickerAdapter.getImageObject(position);
        if (imageFile == null) return;
        String imagePath = imageObject.getImagePath();
        boolean addSuccess = SelectionManager.getInstance().addImageToSelectList(imagePath);
        if (addSuccess) {
            mImagePickerAdapter.notifyItemChanged(position);
        } 
        updateCommitButton();
    }

    //更新按钮状态
    private void updateCommitButton() {
        //改变确定按钮UI
        int selectCount = SelectionManager.getInstance().getSelectPaths().size();
        if (selectCount == 0) {
            mTvCommit.setEnabled(false);
            mTvCommit.setText("发送（0/9）");
            return;
        }
        if (selectCount <= mMaxCount) {
            mTvCommit.setEnabled(true);
            mTvCommit.setText(String.format(getString(R.string.confirm_msg), selectCount, mMaxCount));
            return;
        }
    }


    //切换文件夹，刷新图片
    @Override
    public void onImageFolderChange(View view, int position) {
        ImageFolder imageFolder = mImageFolderList.get(position);
        //更新当前文件夹名
        String folderName = imageFolder.getFolderName();
        if (!TextUtils.isEmpty(folderName)) {
            mTvImageFolders.setText(folderName);
        }
        //更新图片列表数据源
        mImageObjectList.clear();
        mImageObjectList.addAll(imageFolder.getImageObjectList());
        mImagePickerAdapter.notifyDataSetChanged();
        mImageFolderPopupWindow.dismiss();
    }


    //对上层activity返回拍照结果:照片路径集合
    private void commitSelection() {
        ArrayList<String> list = new ArrayList<>(SelectionManager.getInstance().getSelectPaths());
        Intent intent = new Intent();
        intent.putStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES, list);
        setResult(RESULT_OK, intent);
        finish();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mImagePickerAdapter.notifyDataSetChanged();
        updateCommitButton();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }
	
	private void findAllId(){
        mTvTitle =(TextView) findViewById(R.id.tv_actionBar_title);
        mTvCommit = (TextView)findViewById(R.id.tv_actionBar_commit);
        mTvImageTime = (TextView)findViewById(R.id.tv_image_time);
        mRecyclerView =(RecyclerView) findViewById(R.id.rv_main_images);
        mImagePickerAdapter.setOnItemClickListener(this);
        mRlBottom = (RelativeLayout) findViewById(R.id.rl_main_bottom);
        mTvImageFolders =(TextView) findViewById(R.id.tv_main_imageFolders);
	}
	
	private void setAllClick(){
		if (!TextUtils.isEmpty(mTitle)) {
            mTvTitle.setText(mTitle);
        }
        findViewById(R.id.iv_actionBar_back).setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					setResult(RESULT_CANCELED);
					finish();
				}
			});
        mTvCommit.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					commitSelection();
				}
			});
        mTvImageFolders.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View view) {
					if (mImageFolderPopupWindow != null) {
						mImageFolderPopupWindow.showAsDropDown(mRlBottom, 0, 0);
					}
				}
			});
	}

}
